package com.java.jvm.loader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义类加载器
 */
public class SimpleAppClassLoader extends ClassLoader{

     /**定义类加载时的基础路径*/
     private String baseDir;

    public SimpleAppClassLoader(String baseDir) {
        this.baseDir = baseDir;
    }

    /**
     * 查找类、校验类、创建Class字节码对象
     * @param className 类全名(包名.类全名,例如pkg.Hello)
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        //1.定义查找查找路径
        String classDir=className.replace(".", "\\");//pkg.Hello->pkg\\Hello
        String absClassDir=baseDir+classDir+".class";
        //2.判定文件是否存在
        File file=new File(absClassDir);
        if(!file.exists())
            throw new ClassNotFoundException();
        //3.从指定路径下读取类
        InputStream in=null;
        try {
            in = new FileInputStream(file);
            byte[] buf = new byte[in.available()];
            int len = in.read(buf);
        //4.创建字节码对象(defineClass方法不要重写，方法内部会做字节码校验)
            return defineClass(className, buf, 0, len);
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }finally{
            if(in!=null)try{in.close();}catch(Exception e){}
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String baseDir="E:\\TCGBIV\\DEVCODES\\jht\\";
        SimpleAppClassLoader classLoader=
                new SimpleAppClassLoader(baseDir);
        Class<?> aClass = classLoader.loadClass("pkg.Hello");
        Object o1 = aClass.newInstance();
    }
}
